# Create your views here.
from django.http import JsonResponse

from common import common_response, format_conversion
from log.globel_log import Logger
from mysite import mysql_db
import json
import requests as rq

url_prefix = 'https://explorer.whitecoin.info/api/'

log = Logger(level="debug").logger

"""
根据主键获取单个订单
"""


def get_order_by_order_id(request):
    if request.session.get('is_login', None):
        if request.method == "GET":
            request_data = format_conversion.underline_dict(request.GET)
            order_id = request_data.get('order_id')
            if not order_id:
                print('order_id is Null!')
                return JsonResponse(common_response.handle_response({}), json_dumps_params={'ensure_ascii': False})
            else:
                # 打开数据库连接
                db = mysql_db.connect_mysql(mysql_db.MYSQL_DATABASE_PYTHON_PROJECT)
                # 使用cursor()方法获取操作游标
                cursor = db.cursor()
                try:
                    # SQL 查询语句
                    sql = "SELECT order_status, order_no, create_time, update_time FROM `order`  \
                                     WHERE order_id = {}".format(order_id)
                    print('查询的sql语句：', sql)
                    # 执行SQL语句
                    cursor.execute(sql)
                    # 获取所有记录列表
                    # 获取所有记录列表
                    results = cursor.fetchall()
                    result = {}
                    for row in results:
                        result['orderStatus'] = row[0]
                        result['orderNo'] = row[1]
                        # 时间格式化
                        result['createTime'] = row[2].strftime("%Y-%m-%d %H:%M:%S")
                        result['updateTime'] = row[3].strftime("%Y-%m-%d %H:%M:%S")

                    # 关闭数据库连接
                    close_conn(db, cursor)
                    return JsonResponse(common_response.handle_response(result),
                                        json_dumps_params={'ensure_ascii': False})
                except Exception as e:
                    print("get_order_by_order_id exception: {0}".format(e))
                    # 关闭数据库连接
                    close_conn(db, cursor)
                    return JsonResponse(common_response.handle_response({}, 1),
                                        json_dumps_params={'ensure_ascii': False})
        else:
            print("not support request method!")
            return JsonResponse(common_response.handle_response({}, 1),
                                json_dumps_params={'ensure_ascii': False})
    else:
        return JsonResponse(common_response.handle_response("user is not login!", 1),
                            json_dumps_params={'ensure_ascii': False})


"""
根据交易id获取单个交易信息，发送POST请求
"""


def get_transaction_detail_by_tx_id(request):
    if request.session.get('is_login', None):
        if request.method == "GET":
            request_data = format_conversion.underline_dict(request.GET)
            op_type = request_data.get('op_type')
            trx_id = request_data.get('trx_id')
            if not op_type:
                log.info('op_type is Null!')
                return JsonResponse(common_response.handle_response({}), json_dumps_params={'ensure_ascii': False})
            if not trx_id:
                log.info('trx_id is Null!')
                return JsonResponse(common_response.handle_response({}), json_dumps_params={'ensure_ascii': False})
            post_data = {'opType': op_type, 'trxId': trx_id}
            url = url_prefix + "queryTransactionDetail"
            json_data = json.dumps(post_data)
            header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                           "Content-Type": "application/json;charset=UTF-8"}
            res = rq.post(url=url, data=json_data, headers=header_dict)  # 发起请求
            result = res.json()  # 将获取到的数据变成json类型
            log.info('根据 %s 调用区块浏览器获取响应数据 %s', trx_id, result)
            if result:
                ret_code = result['retCode']
                if ret_code == 200:
                    ret_data = result['data']
                    return JsonResponse(common_response.handle_response(ret_data),
                                        json_dumps_params={'ensure_ascii': False})
                else:
                    return JsonResponse(common_response.handle_response({}, 1),
                                        json_dumps_params={'ensure_ascii': False})
            else:
                return JsonResponse(common_response.handle_response({}, 1),
                                    json_dumps_params={'ensure_ascii': False})

        else:
            log.error('not support request method!')
            return JsonResponse(common_response.handle_response({}, 1),
                                json_dumps_params={'ensure_ascii': False})
    else:
        return JsonResponse(common_response.handle_response("user is not login!", 1),
                            json_dumps_params={'ensure_ascii': False})


# 关闭数据库连接
def close_conn(conn, cursor):
    conn.close()
    cursor.close()
